package pswvclass.pswvandroid2.com.category;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.Home;
import pswvclass.pswvandroid2.com.po.Category;
import pswvclass.pswvandroid2.com.util.HttpUtils;

/**
 * Created by Administrator on 2018/11/2.
 */

/**
 * 长按菜单响应函数
 */
public class CategoryList extends Fragment implements View.OnClickListener {
    private int MID;
    private ListView listView;
    private String tag = "Goal";
    private TextView categoryId;
    private TextView name;
    private Button category_add;
    private Button category_search;
    private TextView text_search;
    protected static final int NO_ADD = 2;
    protected static final int SUCCESS = 0;
    protected static final int ERROR = 1;
    protected static final int DELE_SUCCESS = 3;
    protected static final int SEE_SUCCESS = 4;
    protected static final int EDIT_SUCCESS = 5;
    protected static final int CATEGORY_SUCCESS = 6;

    private List<Category> datas = new ArrayList<Category>();
    private String path = "";
    private TextView tv_status;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.pswv_category_list, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        text_search = (TextView) getView().findViewById(R.id.text_search);
        category_add = (Button) getView().findViewById(R.id.category_add);
        category_search = (Button) getView().findViewById(R.id.category_search);
        category_add.setOnClickListener(this);
        category_search.setOnClickListener(this);
        load();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    List<Category> datas = new ArrayList<Category>();
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject temp = (JSONObject) data.get(i);
                            Category ca = new Category();
                            ca.setkCategoryId(temp.getInt("categoryId"));
                            ca.setkName(temp.getString("name"));
                            datas.add(ca);
                        }
                        listView = (ListView) getView().findViewById(R.id.pswv_category_list);
                        listView.setAdapter(new MyAdapter(getContext(), datas));
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case CATEGORY_SUCCESS:
                    List<Category> datas1 = new ArrayList<Category>();
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject temp = (JSONObject) data.get(i);
                            Category ca = new Category();
                            ca.setkCategoryId(temp.getInt("categoryId"));
                            ca.setkName(temp.getString("name"));
                            datas1.add(ca);
                        }
                        listView = (ListView) getView().findViewById(R.id.pswv_category_list);
                        listView.setAdapter(new MyAdapter(getContext(), datas1));

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ERROR:
                    Toast.makeText(getContext(), "连接错误 ....", Toast.LENGTH_SHORT).show();
                    break;
                case NO_ADD:
                    Toast.makeText(getContext(), " 没有查询到....", Toast.LENGTH_SHORT).show();
                    break;
                case DELE_SUCCESS:
                    Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();

                    break;
                case SEE_SUCCESS:
                    try {
                        JSONObject data = (JSONObject) msg.obj;
                        CategorySee cs = new CategorySee();
                        Bundle bundle = new Bundle();
                        bundle.putString("name", data.getString("name"));
                        cs.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, cs).commit();

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v(tag, e + "");
                    }
                    break;
                case EDIT_SUCCESS:
                    try {
                        JSONObject data = (JSONObject) msg.obj;
                        CategoryEdit ce = new CategoryEdit();
                        Bundle bundle = new Bundle();
                        bundle.putInt("editid", data.getInt("id"));
                        bundle.putString("name", data.getString("name"));
                        ce.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, ce).commit();

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v(tag, e + "");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void load() {
        new Thread() {
            public void run() {
                try {
                    HttpUtils hu = new HttpUtils();
                    String data2;
                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/categoryAcion/listAll";
                    final Map<String, String> map1 = new HashMap<String, String>();
                    data2 = hu.submitPostData(src, "utf-8");
                    JSONObject jsonObj = new JSONObject(data2);
                    int result = Integer.parseInt(jsonObj.getString("code"));
                    JSONArray jsonArray = jsonObj.getJSONArray("response");
                    if (result == 0) {
                        Message msg = Message.obtain();
                        msg.what = SUCCESS;
                        msg.obj = jsonArray;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = ERROR;
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }


    class MyAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {
        private LayoutInflater mInflater;
        private List<Category> datas;

        public MyAdapter(Context context, List<Category> contentList) {
            this.mInflater = LayoutInflater.from(context);
            this.datas = contentList;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {

            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getContext(), R.layout.pswv_category_list_see, null);
            categoryId = (TextView) view.findViewById(R.id.categoryId);
            name = (TextView) view.findViewById(R.id.name);
            Category ca = datas.get(position);
            categoryId.setText(String.valueOf(datas.get(position).getkCategoryId()));
            name.setText(datas.get(position).getkName());
            ((ListView) parent).setOnItemClickListener(this);
            return view;
        }

        private void showDialog() {

        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, final View view, final int i, long l) {
            PopupMenu popup = new PopupMenu(getContext(), view);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.category_meun, popup.getMenu());
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    //当点击时弹出被点击象标题

                    switch (item.getItemId()) {
                        case R.id.category_del:
                            final Category ca = datas.get(i);
                            new Thread() {
                                public void run() {
                                    try {
                                        HttpUtils hu = new HttpUtils();
                                        String data2;
                                        final String src = getResources().getString(R.string.src_mysql) + "pswv/api/categoryAcion/remove";
                                        final Map<String, String> map1 = new HashMap<String, String>();
                                        map1.put("id", ca.getkCategoryId() + "");
                                        data2 = hu.submitPostData(src, map1, "utf-8");
                                        JSONObject jsonObj = new JSONObject(data2);
                                        int result = Integer.parseInt(jsonObj.getString("code"));
                                        if (result == 0) {
                                            Message msg = Message.obtain();
                                            msg.what = DELE_SUCCESS;
                                            mHandler.sendMessage(msg);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.v(tag, e + "");
                                    }
                                }
                            }.start();
                            datas.remove(i);
                            notifyDataSetChanged();
                            break;
                        case R.id.category_edit:
                            final Category ca2 = datas.get(i);
                            new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        HttpUtils hu = new HttpUtils();
                                        String data2;
                                        final String src = getResources().getString(R.string.src_mysql) + "pswv/api/categoryAcion/queryById";
                                        final Map<String, String> map1 = new HashMap<String, String>();
                                        map1.put("id", ca2.getkCategoryId() + "");
                                        data2 = hu.submitPostData(src, map1, "utf-8");
                                        JSONObject jsonObj = new JSONObject(data2);
                                        JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                                        int result = Integer.parseInt(jsonObj.getString("code"));
                                        if (result == 0) {
                                            Message msg = Message.obtain();
                                            msg.obj = jsonObj1;
                                            msg.what = EDIT_SUCCESS;
                                            mHandler.sendMessage(msg);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.v(tag, e + "");
                                    }
                                }
                            }.start();
                            break;
                        case R.id.category_see:

                            final Category ca3 = datas.get(i);
                            new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        HttpUtils hu = new HttpUtils();
                                        String data2;
                                        final String src = getResources().getString(R.string.src_mysql) + "pswv/api/categoryAcion/queryById";
                                        final Map<String, String> map1 = new HashMap<String, String>();
                                        map1.put("id", ca3.getkCategoryId() + "");
                                        data2 = hu.submitPostData(src, map1, "utf-8");
                                        JSONObject jsonObj = new JSONObject(data2);
                                        JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                                        int result = Integer.parseInt(jsonObj.getString("code"));
                                        if (result == 0) {
                                            Message msg = Message.obtain();
                                            msg.obj = jsonObj1;
                                            msg.what = SEE_SUCCESS;
                                            mHandler.sendMessage(msg);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.v(tag, e + "");
                                    }
                                }
                            }.start();
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
            popup.show();
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.category_add:

                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.realtabcontent, new CategoryAdd()).commit();
                //  startActivity(new Intent(getContext(), RiskAdd.class));
                break;
            case R.id.category_search:
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/categoryAcion/search";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            String name = text_search.getText().toString().trim();
                            map1.put("name", name);
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                            JSONArray jsonArray = jsonObj1.getJSONArray("list");
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.obj = jsonArray;
                                msg.what = CATEGORY_SUCCESS;
                                mHandler.sendMessage(msg);
                            } else {
                                Message msg = Message.obtain();
                                msg.what = NO_ADD;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                    Button kword_page = (Button) getActivity().findViewById(R.id.kword_page);
                    Button risk_page = (Button) getActivity().findViewById(R.id.risk_page);
                    Button need_page = (Button) getActivity().findViewById(R.id.need_page);
                    kword_page.setVisibility(getView().VISIBLE);
                    risk_page.setVisibility(getView().VISIBLE);
                    need_page.setVisibility(getView().VISIBLE);
                    kword_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    risk_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    need_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, new Home()).commit();
                    return true;
                }
                return false;
            }
        });
    }
}
